import java.io.File;
import java.util.Scanner;

public class MiniProgram1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入要查找的目录: ");

        File rootDir = new File(scan.next());
        while(!rootDir.isDirectory()) {
            System.out.println("您输入的目录不正确!");
            System.out.println("请重新输入: ");

            rootDir = new File(scan.next());
        }

        System.out.println("请输入要查找的关键词: ");
        String target = scan.next();

        scanDir(rootDir,target);
    }

    private static void scanDir(File rootDir, String target) {
        System.out.println("当前访问: " + rootDir.getParentFile());

        File[] files = rootDir.listFiles();
        if(files == null) return;

        for(File f : files) {
            if(f.isDirectory()) {
                scanDir(f,target);
            } else {
                checkDelete(f,target);
            }
        }

    }

    private static void checkDelete(File f, String target) {
        if(f.getName().contains(target)) {
            System.out.println(target + " 被包含在" + f.getParentFile() + " 中");
            System.out.println("是否删除" + target + " 文件? (Y / N) ");

            Scanner scanner = new Scanner(System.in);
            String choice = scanner.next();

            if(choice.equals("Y") || choice.equals("y")) {
                boolean flg = f.delete();
                if(flg)
                    System.out.println("删除成功!");
                else
                    System.out.println("删除失败!");
            }
        }
    }
}
